<?php

class LocationcontactsController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),

            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }


    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($custno = NULL, $locno = NULL)
    {
        $custno = Yii::app()->user->custno;
        $model = new Locationcontacts;
        if ($custno != NULL && $locno != NULL) {
            $model->custno = $custno;
            $model->locno = $locno;
        }
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $model->custno,
            'locno' => $model->locno,
        ));
        if (isset($_POST['Locationcontacts'])) {
            $model->attributes = $_POST['Locationcontacts'];
            if ($model->save()
            )
                //go to contacts list of a location
                $this->redirect(array('index', 'id' => $location->id));
        }

        $customer = Customers::model()->find('custno=:custno', array('custno' => $custno));
        $this->render('create', array(
            'model' => $model,
            'customer' => $customer,
            'location' => $location,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $model->custno,
            'locno' => $model->locno,
        ));
        if (isset($_POST['Locationcontacts'])) {
            $model->attributes = $_POST['Locationcontacts'];
            if ($model->save())
                $this->redirect(array('index', 'id' => $location->id));
        }

        $customer = Customers::model()->find('custno=:custno', array('custno' => $model->custno));
        $this->render('update', array(
            'model' => $model,
            'location' => $location,
            'customer' => $customer,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {

        $model = $this->loadModel($id);
        $id = Yii::app()->db->createCommand('select * from tbl_locations where custno=:custno AND locno=:locno')->queryScalar(array(
            'custno' => $model->custno,
            'locno' => $model->locno,
        ));
        $model->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(array('index', 'id' => $id));

    }

    /**
     * Lists all models.
     */
    public function actionIndex($id)
    {

        $location = Locations::model()->find('id=:id', array('id' => $id));
        if ($location->custno != Yii::app()->user->custno) throw new CHttpException(404, 'The requested page does not exist.');
        $customer = Customers::model()->find('custno=:custno', array(
            'custno' => $location->custno,
        ));
        outputJsByList(Dispatchdetails::model()->getDepartmentList(), 'department');
        outputJsByList(Dispatchdetails::model()->getPriorityList(), 'priority');

        outputJsByList(JobsClass::getList(), 'job');
        Yii::app()->clientScript->registerScript('type', "var type='-1';", CClientScript::POS_HEAD);
        $caller = getUserRealname(Yii::app()->user->name);
        Yii::app()->clientScript->registerScript('caller', "var caller='$caller';", CClientScript::POS_HEAD);

        $this->render('index', array(
            'customer' => $customer,
            'location' => $location,
        ));
    }


    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Locationcontacts::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'locationcontacts-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAjaxView($id)
    {

        $rs = $this->loadModel($id)->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();

    }


    /*
    * How to implement custno and locno
    */
    public function actionGetLocationcontactsList($custno = NULL, $locno = NULL, $query = NULL, $page = 1, $sort = NULL, $dir = NULL)
    {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0) $page--;
        $order = CJSON::decode($sort);
        $criteria = new CDbCriteria();
        if ($sort != NULL) {
            $criteria->order = $sort != NULL ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL;
        }
        if ($custno != NULL && $locno != NULL) {
            $criteria->compare('custno', $custno);
            $criteria->compare('locno', $locno);
        }
        $contacts = new CActiveDataProvider('Locationcontacts', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 20,
                'currentPage' => $page,
            )
        ));
        $rs = array();
        if (count($contacts->getData()) > 0) {
            $rs['totalCount'] = $contacts->getTotalItemCount();
            $rs['type'] = 'Locationcontacts';
            foreach ($contacts->getData() as $item) {
                $rs['data'][] = $item->getAttributes();
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

}
